package com.cskaoyan.utils;

import com.cskaoyan.demo.mapper.UserMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MyBatisUtil {
    static SqlSessionFactory sqlSessionFactory;
    static SqlSession sqlSession;
    static UserMapper userMapper;

    public static void init() throws IOException {
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        sqlSessionFactory = sqlSessionFactoryBuilder.build(Resources.getResourceAsStream("mybatis-config.xml"));
        sqlSession = sqlSessionFactory.openSession();
         userMapper = sqlSession.getMapper(UserMapper.class);
    }

    public static UserMapper getUserMapper() throws IOException {
        init();
        return userMapper;
    }

    public static void release(){
        if (sqlSession != null){
            sqlSession.commit();
            sqlSession.close();
        }
    }
}
